<template>
	<!-- 优惠券管理 -->
	<div id="tops">
		<div class="Box">
			<div>
				<el-container>
					<el-header class="Header">
						<el-header>
							<!-- 搜索 -->
							<el-form :inline="true" :model="formInline" class="demo-form-inline">
								<el-form-item>
									<el-input v-model="formInline.title" placeholder="请输入优惠券标题" clearable></el-input>
								</el-form-item>
								<el-form-item style="width: 180px">
									<el-select v-model="formInline.type" placeholder="请选择优惠券类型" clearable>
										<el-option label="满减券" :value="1"></el-option>
										<el-option label="全部" value=""></el-option>
									</el-select>
								</el-form-item>
								<el-form-item style="width: 180px">
									<el-select v-model="formInline.status" placeholder="请选择优惠券状态" clearable>
										<el-option label="下架" :value="0"></el-option>
										<el-option label="正常" :value="1"></el-option>
										<el-option label="已过期" :value="-1"></el-option>
										<el-option label="全部" value=""></el-option>
									</el-select>
								</el-form-item>
								<el-form-item>
									<el-button type="primary" icon="el-icon-search" @click="init" v-insert="['promote:coupon:query']">查找</el-button>
									<el-button type="primary" icon="el-icon-edit" @click="(dialogVisible = true),(amend(),(title = '创建'))" v-insert="['promote:coupon:create']">添加</el-button>
									<el-button type="primary" icon="el-icon-download" @click="deriveExcel">当前页导出</el-button>
								</el-form-item>
							</el-form>
						</el-header>
					</el-header>

					<el-main>
						<!-- 表格 -->
						<el-table id="table" :data="tableData" border empty-text="暂无数据" size="mini" v-loading="loading"
						 element-loading-text="正在查询中···">
							<el-table-column prop="id" label="优惠券ID" align="center" sortable>
							</el-table-column>
							<el-table-column prop="title" label="优惠券名称" align="center">
							</el-table-column>
							<el-table-column prop="type" label="优惠券类型" align="center">
								<template slot-scope="scope">
									{{ scope.row.type ? "满减券" : "" }}
								</template>
							</el-table-column>
							<el-table-column prop="description" label="介绍" align="center">
							</el-table-column>
							<el-table-column prop="total" label="优惠券数量" align="center">
							</el-table-column>
							<el-table-column prop="surplus" label="剩余数量" align="center">
							</el-table-column>
							<el-table-column prop="limit" label="每人限领" align="center">
							</el-table-column>

							<el-table-column prop="discount" label="满减金额" align="center">
								<template slot-scope="scope">
									减免{{ scope.row.discount }}元
								</template>
							</el-table-column>
							<el-table-column prop="min" label="最低消费" align="center">
								<template slot-scope="scope">
									满{{ scope.row.min }}元可用
								</template>
							</el-table-column>
							<el-table-column prop="status" label="状态" align="center">
								<template slot-scope="scope">
									<el-tag type="primary" disable-transitions>
										{{ getStayus(scope.row) }}
									</el-tag>
								</template>
							</el-table-column>
							<el-table-column prop="categoryTitle" label="使用类目名称" width="100" align="center">
								<template slot-scope="scope">
									<el-tag type="primary" disable-transitions>{{ scope.row.categoryTitle ? scope.row.categoryTitle : "全部类目" }}</el-tag>
								</template>
							</el-table-column>
							<el-table-column prop="categoryId" label="使用类目ID" width="100" align="center">
							</el-table-column>
							<el-table-column prop="days" label="领券相对天数" align="center">
							</el-table-column>
							<el-table-column prop="gmtStart" label="领券开始时间" align="center">
								<template slot-scope="scope">
									{{ getYMDHMS(scope.row.gmtStart) }}
								</template>
							</el-table-column>
							<el-table-column prop="gmtEnd" label="领券结束时间" align="center">
								<template slot-scope="scope">
									{{ getYMDHMS(scope.row.gmtEnd) }}
								</template>
							</el-table-column>
							<el-table-column label="操作" align="center" width="300">
								<template slot-scope="scope">
									<el-button type="primary" size="mini" @click="supdate(scope.row)" v-insert="['promote:coupon:update']">{{ getType(scope.row) }}</el-button>
									<el-button size="mini" type="primary" @click="(dialogVisible = true),(amend(scope.row)),(title = '编辑')" v-insert="['promote:coupon:update']">编辑</el-button>
									<el-button size="mini" type="danger" @click="dis(scope.row)" v-insert="['promote:coupon:delete']">删除</el-button>
								</template>
							</el-table-column>
						</el-table>
						<!-- 添加修改对话框 -->
						<el-dialog :title="title" :visible.sync="dialogVisible" v-if="dialogVisible" width="50%" :before-close="handleClose">
							<el-form class="demo-ruleForm" ref="roleForm" :rules="rules" :model="roleForm" label-width="100px"
							 label-position="left" status-icon style="margin: 0 5%">
								<el-form-item label="优惠券名称" prop="title" :rules="[{ required: true, message: '优惠券标题不能为空',trigger: 'blur', }]">
									<el-input type="text" v-model="roleForm.title" style="width: 50%"></el-input>
								</el-form-item>
								<el-form-item label="优惠券类型" prop="type">
									<el-select v-model="roleForm.type" placeholder="请选择优惠券类型">
										<el-option label="满减券" :value="1"></el-option>
									</el-select>
								</el-form-item>
								<el-form-item label="介绍" prop="description">
									<el-input type="text" v-model="roleForm.description" style="width: 50%"></el-input>
								</el-form-item>
								<el-form-item label="优惠券数量" prop="total">
									<el-input type="text" v-model="roleForm.total" style="width: 50%">
										<template slot="append">张</template>
									</el-input>
								</el-form-item>
								<el-form-item label="每人限领" prop="limit">
									<el-input type="text" v-model="roleForm.limit" style="width: 50%"><template slot="append">张</template></el-input>
								</el-form-item>
								<el-form-item label="满减金额" prop="discount">
									<el-input type="text" v-model="roleForm.discount" style="width: 50%">
										<template slot="append">元</template>
									</el-input>
								</el-form-item>
								<el-form-item label="最低消费" prop="min">
									<el-input type="text" v-model="roleForm.min" style="width: 50%">
										<template slot="append">元</template>
									</el-input>
								</el-form-item>
								<el-form-item label="优惠卷状态" prop="status">
									<el-select v-model="roleForm.status" placeholder="请选择优惠券类型">
										<el-option label="正常" :value="1"></el-option>
										<el-option label="下架" :value="0"></el-option>
									</el-select>
								</el-form-item>
								<el-form-item label="有效期">
									<el-radio-group v-model="radio1">
										<el-radio-button :label="1">领券相对天数</el-radio-button>
										<el-radio-button :label="0">指定绝对时间</el-radio-button>
									</el-radio-group>
								</el-form-item>
								<el-form-item v-show="radio1 == 1 ? true : false" prop="days">
									<el-input type="text" v-model="roleForm.days" style="width: 50%"><template slot="append">天</template>
									</el-input>
								</el-form-item>
								<el-form-item v-show="radio1 == 0 ? true : false">
									<el-date-picker v-model="roleForm.gmtStart" type="datetime" placeholder="选择日期" style="width: 25%"></el-date-picker>
									至
									<el-date-picker v-model="roleForm.gmtEnd" type="datetime" placeholder="选择日期" style="width: 25%"></el-date-picker>
								</el-form-item>
								<el-form-item label="商品限制范围">
									<el-radio-group v-model="radio2" :disabled="title == '创建' ? false : true">
										<el-radio-button :label="1">全场通用</el-radio-button>
										<el-radio-button :label="0">指定分类</el-radio-button>
									</el-radio-group>
								</el-form-item>
								<el-form-item label="优惠类目" v-show="radio2 == 0 ? true : false" prop="categoryId">
									<el-cascader v-model="roleForm.categoryId" :options="options" :props="{ checkStrictly: true }" :disabled="title == '创建' ? false : true"></el-cascader>
								</el-form-item>
							</el-form>
							<span slot="footer" class="dialog-footer">
								<el-button @click="dialogVisible = false">取 消</el-button>
								<el-button type="primary" @click="determine">确 定</el-button>
							</span>
						</el-dialog>
					</el-main>
					<!-- 分页 -->
					<el-header class="buttom">
						<div class="block">
							<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
							 :page-sizes="[10, 20, 30, 40,50,100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
							 :total="total">
							</el-pagination>
						</div>
					</el-header>
				</el-container>
			</div>
		</div>
	</div>
</template>

<script>
	// import gvft from '../../http/ex.js'
	// import XLSX from 'xlsx' //引入当前页导出所需的插件
	import {
		Copunlist,
		Coupunaddupdate,
		Coupundel,
		CoupStatus,
		Couptree
	} from '../../api/couponmanage.js'
	export default {
		data() {
			const validateTitle = (rule, value, callback) => {
				if (value === '' || value == undefined || value == null) {
					callback(new Error('优惠券标题不能为空'))
				} else {
					callback()
				}
			}
			const validateType = (rule, value, callback) => {
				if (value == '' || value == null) {
					callback(new Error('请选择优惠券类型'))
				} else {
					callback()
				}
			}
			const validateTotal = (rule, value, callback) => {
				if (value === '' || value == undefined || value == null) {
					callback(new Error('优惠券总量不能为空'))
				} else if (Number(value) < Number(this.roleForm.limit)) {
					callback(new Error('优惠券总量不能小于优惠券限领数量，但可以等于'))
				} else {
					callback()
				}
			}
			const validateLimit = (rule, value, callback) => {
				if (value === '' || value == undefined || value == null) {
					callback(new Error('优惠券限领不能为空'))
				} else if (Number(this.roleForm.total) < Number(value)) {
					callback(new Error('优惠券总量不能小于优惠券限领数量，但可以等于'))
				} else {
					callback()
				}
			}
			const validateDiscount = (rule, value, callback) => {
				if (value === '' || value == undefined || value == null) {
					callback(new Error('优惠券折扣金额不能为空'))
				} else if (Number(value) > Number(this.roleForm.min)) {
					callback(new Error('满减门栏不能低于折扣金额，但是可以等于'))
				} else {
					callback()
				}
			}
			const validateMin = (rule, value, callback) => {
				if (value === '' || value == undefined || value == null) {
					callback(new Error('优惠券使用门栏类型'))
				} else if (Number(this.roleForm.discount) > Number(value)) {
					callback(new Error('满减门栏不能低于折扣金额，但是可以等于'))
				} else {
					callback()
				}
			}
			const validateStatus = (rule, value, callback) => {
				if (value == '' || value == null) {
					callback(new Error('请选择优惠券类型'))
				} else {
					callback()
				}
			}
			return {
				downloadLoading: false,
				input: '',
				value1: '',
				tableData: [],
				currentPage: 1,
				pageNo: 1,
				pageSize: 20,
				total: 0,
				loading: true,
				roleForm: {
					title: '',
					type: 1,
					description: '',
					limit: 0,
					total: 0,
					min: 0,
					discount: 0,
					status: 1,
					days: '',
					gmtStart: '',
					gmtEnd: '',
					categoryId: '',
					id: ''
				},
				rules: {
					title: [{
						required: true,
						validator: validateTitle,
						trigger: 'blur'
					}],
					type: [{
						required: true,
						validator: validateType,
						trigger: 'change'
					}],
					total: [{
						required: true,
						validator: validateTotal,
						trigger: 'blur'
					}],
					limit: [{
						required: true,
						validator: validateLimit,
						trigger: 'blur'
					}],
					discount: [{
						required: true,
						validator: validateDiscount,
						trigger: 'blur'
					}],
					min: [{
						required: true,
						validator: validateMin,
						trigger: 'blur'
					}],
					status: [{
						required: true,
						validator: validateStatus,
						trigger: 'blur'
					}]
				},
				title: '',
				formInline: {
					title: '',
					type: null,
					status: null
				},
				nowTime: '',
				radio1: 1,
				dialogVisible: false,
				radio2: 1,
				options: [],
				frame: ''
			}
		},
		mounted() {
			this.init()
			this.nowTime = new Date().getTime()
		},
		created() {
			this.list()
			this.init()
		},
		methods: {
			// 列表渲染
			init() {
				const Renderlist = {
					pageNo: this.pageNo,
					limit: this.pageSize,
					...this.formInline
				}
				Copunlist(Renderlist).then((resspose) => {
					if (resspose.data.errmsg == '成功') {
						this.loading = false
						this.total = resspose.data.data.total
						this.tableData = resspose.data.data.items
					} else {
						setTimeout(() => {
							this.loading = false
						}, 5000)
					}
				})
			},
			// 时间戳转换
			getYMDHMS(timestamp) {
				if (timestamp) {
					const time = new Date(timestamp)
					const year = time.getFullYear().toString().padStart(2) // 获取完整的年份
					const month = (time.getMonth() + 1).toString().padStart(2) // 范围0~11， 跟中国的月份相差1
					const date = time.getDate().toString().padStart(2, '0') // getDate表示获取当前时间对应的月份中的天数
					const hours = time.getHours().toString().padStart(2) // 获取当前小时
					const minute = time.getMinutes().toString().padStart(2) // 获取当前分钟
					const second = time.getSeconds().toString().padStart(2) // 获取当前秒
					return (year + '-' + month + '-' + date + '' + hours + ':' + minute + ':' + second)
				} else {
					return '无'
				}
			},
			// 判断过期
			getStayus(row) {
				if (this.nowTime > row.gmtEnd) {
					return '已过期'
				} else if (row.status) {
					return '正常'
				} else {
					return '下架'
				}
			},
			getType(row) {
				if (this.nowTime > row.gmtEnd) {
					return '已过期'
				} else if (row.status) {
					return '激活'
				} else {
					return '冻结'
				}
			},
			// spu树
			list() {
				Couptree().then((resspose) => {
					this.options = resspose.data.data
				})
			},
			// 编辑添加
			amend(row) {
				console.log(row)
				if (!row) {
					this.roleForm.title = ''
					this.roleForm.type = 1
					this.roleForm.status = 1
					this.roleForm.description = ''
					this.roleForm.limit = 0
					this.roleForm.discount = 0
					this.roleForm.min = 0
					this.roleForm.total = 0
					this.roleForm.categoryId = ''
					this.roleForm.days = ''
				} else {
					// 修改
					this.roleForm = row
					if (row.categoryTitle) {
						this.radio2 = 1
						this.dialogVisible2 = true
					} else {
						this.radio2 = 0
						this.dialogVisible2 = true
					}
					if (row.gmtEnd && row.gmtStart) {
						this.radio1 = 0
						const Time1 = new Date(row.gmtEnd)
						this.roleForm.gmtEnd = Time1.getTime()
						const Time2 = new Date(row.gmtStart)
						this.roleForm.gmtStart = Time2.getTime()
						this.disabled = true
						// setTimeout(() => {}, 10);
					} else {
						this.radio1 = 1
						this.disabled = true
						// setTimeout(() => {}, 10);
					}
				}
			},
			// 确定编辑和添加
			determine() {
				if (this.roleForm.days == '' && (this.roleForm.gmtStart == '' || this.roleForm.gmtEnd == '')) {
					this.$message.error({
						type: 'info',
						message: '请填写优惠卷使用区间息'
					})
				} else {
					this.$refs.roleForm.validate((valid) => {
						if (valid) {
							const data = {
								_mt: this.title == '创建' ? 'addCoupon' : 'updateCoupon',
								title: this.roleForm.title,
								type: this.roleForm.type,
								limit: this.roleForm.limit,
								description: this.roleForm.description,
								total: this.roleForm.total,
								min: this.roleForm.min,
								discount: this.roleForm.discount,
								status: this.roleForm.status,
								days: this.roleForm.days,
								categoryId: this.title == '创建' ? this.roleForm.categoryId[this.roleForm.categoryId.length - 1] : '',
								id: this.roleForm.id,
								gmtStart: this.title.gmtStart,
								gmtEnd: this.title.gmtEnd,
								surplus: this.roleForm.surplus
							}
							Coupunaddupdate(data).then((resspose) => {
								console.log(resspose)
								if (resspose.data.errmsg == '成功') {
									this.dialogVisible = false
									this.init()
									this.$message({
										type: 'success',
										message: this.title == '编辑' ? '更新用户成功' : '添加用户成功'
									})
								} else {
									this.$message.error(resspose.data.errmsg)
								}
							})
						} else {
							return false
						}
					})
				}
			},
			// 修改优惠券状态
			supdate(row) {
				if (row.gmtEnd < this.nowTime) {
					this.$message.error('过期优惠券,建议删除')
				} else {
					const data = {
						id: row.id,
						status: row.status == 1 ? 0 : 1
					}
					console.log(data)
					CoupStatus(data).then((resspose) => {
						console.log(resspose.data)
						if (resspose.data.errmsg == '成功') {
							this.init()
							this.frame ? this.frame.close() : ''
							this.frame = this.$message({
								type: 'success',
								message: '状态更改成功'
							})
						} else {
							this.$message.error(resspose.data.errmsg)
						}
					})
				}
			},
			// 删除
			dis(row) {
				this.$confirm(`此操作将永久删除该用户---'${row.title}'---是否继续?', '提示`, {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						Coupundel(row.id).then((resspose) => {
							console.log(resspose)
							if (resspose.data.errmsg == '成功') {
								this.init()
								this.$message({
									type: 'success',
									message: '删除成功'
								})
							} else {
								this.$message.error({
									type: 'info',
									message: resspose.data.errmsg
								})
							}
						})
					})
					.catch(() => {
						this.$message({
							type: 'info',
							message: '已取消删除'
						})
					})
			},
			handleClose() {
				this.dialogVisible = false
			},
			// 当前页导出
			deriveExcel() {
				// let workbook = XLSX.utils.table_to_book(document.getElementById('table')); //需要在table上定义一个id
				// try {
				// 	XLSX.writeFile(workbook, '优惠券信息.xlsx');
				// 	this.$message({
				// 		type: 'success',
				// 		message: '导出成功,注意查收系统下载文件'
				// 	})
				// } catch (e) {
				// 	this.$message({
				// 		type: 'success',
				// 		message: '导出失败,失败信息:' + e
				// 	})
				// }
				var temp = new Date()
				var date = temp.getFullYear() + '-' + temp.getMonth() + '-' + temp.getDate()
				this.downloadLoading = true
				const _this = this
				import('../../http/XLSX.js').then(excel => {
						const tHeader = [
							'优惠券ID',
							'名称',
							'介绍',
							'类型',
							'最低消费',
							'减免金额',
							'每人限领',
							'优惠券数量',
							'剩余数量',
							'状态',
							'使用类目'
						]
						const filterVal = [
							'id',
							'title',
							'description',
							'type',
							'min',
							'discount',
							'limit',
							'total',
							'surplus',
							'status',
							'cateotry'
						]
						excel.export_json_to_excel2(tHeader, _this.tableData, filterVal, date + ' 优惠券信息')
						_this.downloadLoading = false
					})
					.catch(() => {})
			},
			// 分页
			handleSizeChange(val) {
				this.pageSize = val
				this.init()
			},
			handleCurrentChange(val) {
				this.pageNo = val
				this.init()
			}
		}
	}
</script>

<style lang="less" scoped="scoped">
	// 头部
	#tops {
		width: 100%;
		overflow: hidden;
		// background-color: pink;
	}

	// 头部
	.Box {
		width: 100%;
		overflow: hidden;
		// height: 900px;
	}

	// 底部
	.buttom {
		color: #333;
		// text-align: center;
		width: 100%;
		height: 130px !important;
	}

	// 表头
	.Header {
		// background-color: #B3C0D1;
		color: #333;
		// text-align: center;
		width: 100%;
		height: 90px !important;
		display: flex;
	}

	.el-header {
		background: none !important;
		height: auto !important;
		width: 100%;
		white-space: nowrap;
		overflow: hidden;
		text-align: left;
		line-height: 0 !important;

		.el-input {
			width: 200px;
			margin: 0 3px;
		}
	}

	.demo-form-inline {
		padding-top: 30px;

	}

	.el-main {
		//   background: #666;
		width: 100%;
		white-space: nowrap;
		overflow: hidden;
		// padding-left: 0px !important;
		padding-right: 0px !important;
	}

	.block {
		margin-top: 10px;
	}
</style>
